#include "queue.h"

CQueueParser::CQueueParser()
{
}

CQueueParser::~CQueueParser()
{
/*
map<string, CObject*>::iterator i;
	for(i=objects.begin(); i!=objects.end(); i++)
	{
		delete i->second;
	}
*/
}

void CQueueParser::addObject(const string& name, PObject obj)
{
	objects[name] = obj;
}

void CQueueParser::pushMessage(vector<Message>& msg)
{
	vector<Message>::iterator i;
	for(i=msg.begin(); i!=msg.end(); i++)
		msgQueue.push( (*i) );
}

void CQueueParser::parse(vector<Message>& initMessage)
{
	pushMessage(initMessage);

	while(1)
	{
		map<string, PObject>::iterator i;
		vector<Message> retMsg;
		Message msg;

		if(msgQueue.size()!=0)
		{
			msg = msgQueue.front();
			msgQueue.pop();
		}
		else
		{	//when the queue is empty
			msg.Set("Parser","Master",MSG_QUEUE_EMPTY);
		}

		if(msg.To=="All")
		{	//send this message to all objects
			for(i=objects.begin(); i!=objects.end(); i++)
				i->second->parseMessage(msg, retMsg);

			pushMessage(retMsg);
		}
		else if(msg.To=="Parser")
		{
			if(msg.MsgCode==MSG_EXIT) break;
			else msgToParser(msg, retMsg);
		}
		else
		{	// send message to object pointed in msg.To field
			i=objects.find(msg.To);
			if(i!=objects.end())
			{
				i->second->parseMessage(msg, retMsg);
				pushMessage(retMsg);
			}
			else
			{
				cout << "Message sended from: " << msg.From ;
				cout << "  Code: " << msg.MsgCode;
				cout << "  No such objetct: " << msg.To << endl;
			}
		}
		retMsg.clear();
	}
}

void CQueueParser::msgToParser(Message& msg, vector<Message>& retMsg)
{
/*	switch(msg.MsgCode)
	{
	case MSG_IS_QUEUE_EMPTY:
		Message m("Parser", "Master", (msgQueue.size()==0) ? MSG_QUEUE_EMPTY : MSG_QUEUE_NOT_EMPTY);
		retMsg.push_back(m);
		break;
	}
*/

}